import React, { Component } from 'react';
import { Tag, Checkbox, Input, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import httpRequest from '@/utils/request';
import './style.less';

const colors: string[] = [
  'magenta',
  'red',
  'volcano',
  'orange',
  'gold',
  'lime',
  'green',
  'cyan',
  'blue',
  'geekblue',
  'purple',
];

export interface TagsState {
  selectValue: {
    id: string;
    tagname: string;
  }[];
  tagList: {
    id: string;
    tagname: string;
  }[];
  inputVisible: boolean;
  inputValue: string;
}

export interface TagsProps {
  selectValue: {
    id: string;
    tagname: string;
  }[];
}

class Tags extends Component<TagsProps, TagsState> {
  input!: HTMLInputElement;
  defaultValue!: string[];
  static defaultProps: TagsProps = {
    selectValue: [],
  };
  constructor(props: TagsProps) {
    super(props);
    this.state = {
      tagList: [],
      inputVisible: false,
      inputValue: '',
      selectValue: [],
    };
    this.getTagsList();
    this.defaultValue = [];
    this.setDefaultValue();
  }

  setDefaultValue = () => {
    if (!this.props.selectValue.length) return;
    const res: string[] = [];
    for (let tag of this.props.selectValue) {
      res.push(tag.id);
    }
    this.defaultValue = res;
  };

  addTags = async (tagname: string) => {
    try {
      const res = await httpRequest.post('/tag', {
        tagname,
      });
      message.success('添加成功');
    } catch (error) {}
  };

  getTagsList = async () => {
    try {
      const res = await httpRequest.get('/tag');
      this.setState(() => ({
        tagList: res.data,
      }));
    } catch (error) {
      console.error(error);
    }
  };

  deleteTag = async (id: string) => {
    try {
      const res = await httpRequest.delete(`/tag/${id}`);
      console.log(res);
      await this.getTagsList();
    } catch (error) {}
  };

  onChange = (checkedValues: any[]) => {
    const _selectValue: { id: string; tagname: string }[] = [];
    for (let id of checkedValues) {
      const target = this.state.tagList.find(tag => tag.id === id);
      if (target) _selectValue.push(target);
    }
    this.setState({
      selectValue: _selectValue,
    });
  };

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  };

  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };

  handleInputConfirm = async () => {
    try {
      const { inputValue } = this.state;
      if (inputValue) {
        await this.addTags(this.state.inputValue);
        await this.getTagsList();
        this.setState(() => ({
          inputValue: '',
        }));
      }
      this.setState(() => ({
        inputVisible: false,
      }));
    } catch (error) {}
  };

  saveInputRef = (input: HTMLInputElement) => {
    this.input = input;
    return;
  };

  renderAdd() {
    return this.state.inputVisible ? (
      <Input
        ref={this.saveInputRef}
        type="text"
        size="small"
        style={{ width: 78 }}
        value={this.state.inputValue}
        onChange={this.handleInputChange}
        onBlur={this.handleInputConfirm}
        onPressEnter={this.handleInputConfirm}
      />
    ) : (
      <Tag onClick={this.showInput} className="site-tag-plus">
        <PlusOutlined /> 新增
      </Tag>
    );
  }

  render() {
    return (
      <Checkbox.Group
        defaultValue={this.defaultValue}
        className="tags"
        onChange={this.onChange}
      >
        {this.state.tagList.map((tag, index) => (
          <Tag
            onClose={e => {
              this.deleteTag(tag.id);
              e.preventDefault();
            }}
            color={colors[Number(index) % 11]}
            closable
            key={tag.id}
          >
            <Checkbox value={tag.id}>{tag.tagname}</Checkbox>
          </Tag>
        ))}
        {this.renderAdd()}
      </Checkbox.Group>
    );
  }
}

export default Tags;
export { colors }; 
